import process from "node:process"
import {spawn} from "node:child_process";
import * as step from "@flow/step"


export async function runUserScript(): Promise<number> {
    let stepArgs = process.argv.slice(2);
    if (stepArgs.length == 0) {
        return Promise.resolve(0)
    }
    return await new Promise<number>((resolve, reject) => {
        const userScriptFile = stepArgs[0] as string
        const args = [userScriptFile]
        const shellProcess = spawn("sh", args)

        shellProcess.stdout.setEncoding('utf8');
        shellProcess.stdout.on('data', function(data) {
            process.stdout.write(data)
        });

        shellProcess.stderr.setEncoding('utf8');
        shellProcess.stderr.on('data', function(data) {
            process.stderr.write(data)
        });

        shellProcess.on('close', function (code: number) { // Should probably be 'exit', not 'close'
            resolve(code);
        });

        shellProcess.on('error', function (err: Error) {
            step.error(`Invoke user script failed, ${err.message}`)
            reject(-1);
        });
    })
}
